package com.ibm.demoBankJSF.backend;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


/**
 * Clase que conecta con la base de datos
 * 
 * @author Sergio Villegas, Javier Trapero y Ruben Ropero
 */

public class Conexion {

	private static DataSource ds;
	
	private synchronized static void  initDatasource(){
		
		try {
			InitialContext cxt = new InitialContext();
			Context envContext = (Context) cxt.lookup("java:/comp/env");
			ds = (DataSource) envContext.lookup("DEMOBANK");
		} catch (NamingException e) {
			e.printStackTrace();
		}
		 
	}
	
	public static Connection getConnection(){
		Connection conn = null;
		try {
			if(ds==null) initDatasource();
				conn = ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return conn;
		
	}
	
	public static void putConnection(Connection con) throws SQLException{
		if(con!=null && !con.isClosed()) con.close();
	}
}